<template>
    <div class="mqtt-panel">
        <div class="panel-header">
            <h4>MQTT配置</h4>
            <a-button
                type="link"
                size="small"
                icon="reload"
                @click="loadMqttConfig"
            >
                刷新
            </a-button>
        </div>
        
        <div v-if="loading" class="loading-text">
            加载中...
        </div>
        
        <div v-else-if="mqttConfigs.length > 0" class="mqtt-info">
            <div 
                v-for="config in mqttConfigs" 
                :key="config.id" 
                :class="['config-card', { 'selected': selectedConfigId === config.id }]"
                @click="handleSelectConfig(config.id)"
            >
                <div class="config-left">
                    <a-tag color="blue">{{ config.name || '未命名' }}</a-tag>
                </div>
                <div class="config-right">
                    <a-tag color="green">{{ config.address || '未配置' }}</a-tag>
                    <span class="port-separator">:</span>
                    <a-tag color="orange">{{ config.port || '未配置' }}</a-tag>
                </div>
            </div>
        </div>
        
        <div v-else class="empty-text">
            暂无MQTT配置
        </div>
    </div>
</template>

<script>
export default {
    name: 'MqttPanel',
    data() {
        return {
            mqttConfigs: [],
            loading: false,
            selectedConfigId: null
        }
    },
    mounted() {
        this.loadMqttConfig()
    },
    methods: {
        async loadMqttConfig() {
            this.loading = true
            try {
                const res = await this.$tabManager.settingsTabManager.getAllNetworkMqttSettings()
                console.log('✅ [MqttPanel] 获取MQTT配置原始数据', res)
                // 如果 data 是字符串，则解析它
                let data = {}
                if (typeof res === 'string') {
                    data = JSON.parse(res)
                }
                
                // 确保 data 是数组
                const dataArray = Array.isArray(data) ? data : []
                
                // 提取需要的字段：name, address, port
                this.mqttConfigs = dataArray.map(item => ({
                    id: item.id,
                    name: item.config?.name || item.name || '未命名',
                    address: item.config?.address || '未配置',
                    port: item.config?.port || '未配置'
                }))
                
                // 加载完成后发送补全数据
                this.$nextTick(() => {
                    this.emitCompletionData()
                })
            } catch (error) {
                console.error('加载MQTT配置失败:', error)
                this.$message.error('加载MQTT配置失败')
            } finally {
                this.loading = false
            }
        },
        handleSelectConfig(configId) {
            this.selectedConfigId = configId
            this.$emit('select', configId)
        },
        // 提供给父组件调用的刷新方法
        refresh() {
            this.loadMqttConfig()
        },
        // 提取补全数据并发送给父组件
        emitCompletionData() {
            const completions = []
            
            // 遍历所有 MQTT 配置，提取 name 字段
            this.mqttConfigs.forEach(config => {
                if (config.name && config.name !== '未命名') {
                    completions.push({
                        caption: config.name,
                        value: config.name,
                        meta: 'MQTT',
                        score: 1550, // 优先级设置在设备和变量之间
                        docHTML: `<b>${config.name}</b><br/>类型: MQTT配置<br/>地址: ${config.address}:${config.port}`
                    })
                }
            })
            
            console.log('📤 [MqttPanel] 发送补全数据，共', completions.length, '个')
            
            // 发送给父组件
            this.$emit('update-completions', completions)
        }
    }
}
</script>

<style scoped>
.mqtt-panel h4 {
    font-size: 14px;
    font-weight: 500;
    margin: 0;
    color: #262626;
}
.panel-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
}
.mqtt-info {
    display: flex;
    flex-direction: column;
    gap: 12px;
}
.config-card {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    padding: 12px 16px;
    background: #fff;
    border: 2px solid #e8e8e8;
    border-radius: 6px;
    cursor: pointer;
    transition: all 0.3s ease;
}
.config-card:hover {
    border-color: #40a9ff;
    box-shadow: 0 2px 8px rgba(64, 169, 255, 0.15);
}
.config-card.selected {
    border-color: #1890ff;
    background: #e6f7ff;
    box-shadow: 0 2px 8px rgba(24, 144, 255, 0.2);
}
.config-left {
    display: flex;
    align-items: center;
}
.config-right {
    display: flex;
    align-items: center;
    gap: 4px;
}
.port-separator {
    font-size: 16px;
    font-weight: bold;
    color: #595959;
    margin: 0 2px;
}
.loading-text,
.empty-text {
    text-align: center;
    padding: 20px;
    color: #8c8c8c;
    font-size: 13px;
}
</style>

